package midlet;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
/**
 *  Main class for menu
 * 
 * @author DJ
 */
public class midlet extends MIDlet implements CommandListener{
    
	Display display = Display.getDisplay(this);
	public Form options;
	public Form editoroptions;
	
	public Form debuginfo;
  Alert al;
  List mainmenu;
  List playermenu;
  TextBox musiclibrary=new TextBox("Enter your music names :","Beatles Rock !!",1000,TextField.ANY);
  TextBox editor=new TextBox("TextBox Editor :","Welcome to the SandBox",1000,TextField.ANY);
  Ticker menuticker=new Ticker("Select anything !!!");
  DateField date=new DateField("Today's : ",DateField.DATE);
  DateField time=new DateField("Time :",DateField.TIME);
  
  Gauge autoload=new Gauge("Auto-Load",true,1,1);
 
  TextField mp3name=new TextField("Music Filename","file:///E:/test.mp3",50,0);
  TextField textfilename=new TextField("Text File Name","file:///E:/text.txt",50,0);
  TextField libraryfilename=new TextField("Library File Names","file:///E:/allmusic.txt",50,0);
  TextField settingsfilename=new TextField("Settings File Name","file:///E:/allsettings.txt",50,0);
  
  Command Enter= new Command("Enter",Command.BACK,0);
  Command MusicEnter=new Command("Go",Command.BACK,0);
  Command mainscreen= new Command("Main",Command.SCREEN,1);
  Command Exit= new Command("Exit",Command.STOP,2);
  Command Full=new Command("FullScreen",Command.SCREEN,3);
  Command EditorOptions=new Command("Options",Command.SCREEN,3);
  
  Command ReloadEditor=new Command("Load",Command.SCREEN,4);
  Command SaveEditor=new Command("Save",Command.SCREEN,4);
  
  Command Playcmd=new Command("Play",Command.SCREEN,4);
  
  Blocks cd;
  Player play;
  game gam;
  playerthread visualplay;
  
  long musicpos=0;
  boolean paused=false;
  
  public String readFile(String path)
  {InputStream is=null;
  FileConnection fc;
            fc = null;
  String str="";
  try{
  fc=(FileConnection)Connector.open(path,Connector.READ_WRITE);
  if(fc.exists()){
	  int size=(int)fc.fileSize();
	  is=fc.openInputStream();
	  byte bytes[]=new byte[size];
	  is.read(bytes, 0, size);
	  str=new String(bytes,0,size);
	  }
  }
  catch(Exception e)
  {//e.printStackTrace();
  Alert error=new Alert("Error",e.getMessage(),null,AlertType.INFO);
  error.setTimeout(2000);
  display.setCurrent(error);debuginfo.append('\n'+e.getMessage());}
  finally
  {
	  try{
		  if(null!=is)is.close();
		  }catch(Exception e){System.out.println(e.getMessage());
                  debuginfo.append('\n'+e.getMessage());
		  }}
return str;
  }
  void writeTextFile(String fName, String text)
  {
	  OutputStream os=null;
	  FileConnection fconn=null;
	  try
	  {
		  fconn=(FileConnection)Connector.open(fName, Connector.READ_WRITE);
		  if(!fconn.exists()){
			  fconn.create();
		  }
		  os=fconn.openDataOutputStream();
		  os.write(text.getBytes());
		  fconn.setHidden(false);
		  fconn.setReadable(true);
                  
                  //os.write(0);
                  //os.write(0xFF);
	  }
	  catch(Exception e)
	  {
		 //e.printStackTrace();
                debuginfo.append('\n'+e.getMessage());
		  
	  }
	  finally
	  {
		  try{
			  if(null!=os)
			  {
				  os.close();
			  }
			  if(null!=fconn)
			  {
				  fconn.close();			  
			  }
		  }
		  catch(Exception e)
		  {//e.printStackTrace();
                    debuginfo.append('\n'+e.getMessage());
		  }
		  
	  }
		  
	  }
	  
  
  public midlet(){
	
      display.setCurrent(mainmenu);
      
      debuginfo=new Form("Errors");
  debuginfo.addCommand(mainscreen);
  debuginfo.setCommandListener(this);
  debuginfo.append("Found Errors:");
      
  //TextBox Setup
  editor.addCommand(mainscreen);
  editor.addCommand(EditorOptions);
  editor.addCommand(SaveEditor);
  editor.addCommand(ReloadEditor);
  
  editor.setCommandListener(this);
  editor.setTicker(new Ticker("SmallEditor"));
  if(autoload.getValue()==1)
	  {try{editor.setString(readFile(textfilename.getString()));}
  catch(Exception  e)
  {debuginfo.append('\n'+e.getMessage());
 
//  editor.setMaxSize(1000);
  editor.setString("EmptyFile");
  }}
  
  //List Set-Up
  mainmenu=new List("Main Menu :",3);
  mainmenu.append("Date-Time",null);
  mainmenu.append("Editor",null);
  mainmenu.append("Options",null);
  mainmenu.append("Blocks",null);
  mainmenu.append("Game",null);
  mainmenu.append("Music Creater",null);
  mainmenu.append("Music Player",null);
  mainmenu.append("Errors",null);
  mainmenu.addCommand(Exit);
  mainmenu.addCommand(Enter);
  mainmenu.setCommandListener(this);
  mainmenu.setTicker(menuticker);
  
  musiclibrary.setString(readFile(libraryfilename.getString()));
  musiclibrary.addCommand(mainscreen);
  musiclibrary.addCommand(Playcmd);
  musiclibrary.setCommandListener(this);
  
  playermenu=new List("Music Menu :",3);
  playermenu.append("Play", null);
  playermenu.append("Stop", null);
  playermenu.append("Pause", null);
  playermenu.append("Add to library", null);
  playermenu.append("Visual Player", null);
  playermenu.append("Music Library", null);
  playermenu.addCommand(mainscreen);
  playermenu.addCommand(MusicEnter);
  playermenu.setCommandListener(this);
  
  //Alert set-up
  al=new Alert("DateAlert");
  al.setType(AlertType.INFO);
  al.setString(new Date().toString());
  al.setTitle("Current Date");
  al.setTimeout(2000);

  //Options Setup
  options=new Form("Options");
  
  editoroptions=new Form("Options");
  options.append("General Options : ");
  options.addCommand(mainscreen);
  options.setCommandListener(this);
  editoroptions.addCommand(Enter);
  editoroptions.addCommand(SaveEditor);
  editoroptions.addCommand(ReloadEditor);
  
  editoroptions.setCommandListener(this);
  
  date.setDate(new java.util.Date());
  time.setDate(new java.util.Date());
  options.append(date);
  options.append(time);
  options.append(mp3name);
  options.append(libraryfilename);
  options.append(settingsfilename);
  
  editoroptions.append(textfilename);
  editoroptions.append(autoload);
  
  
      }

public void startApp(){
  display.setCurrent(mainmenu);
  }

  public void pauseApp(){
cd=null;options=null;}
  public void destroyApp(boolean unconditional){

  options=null;
  al=null;
  editor=null;
  musiclibrary=null;
  cd=null;
  notifyDestroyed();}
    
  public void commandAction(Command c,Displayable d)
  {      
      if(c==mainscreen)
		  display.setCurrent(mainmenu);
  else if(c==Enter)
  {
	  switch(mainmenu.getSelectedIndex())
	  {
	  case 0:
		  display.setCurrent(al);
		  break;
	  case 1:
		  display.setCurrent(editor);
		  break;
	  case 2:
		  display.setCurrent(options);
		  break;
	  case 3:		 
cd=new Blocks(debuginfo,display,this);
cd.setCommandListener(cd);
cd.setTitle("Canvas");
		  display.setCurrent(cd);
		  break;
	  case 4:
		  gam=new game();
display.setCurrent(gam);
		 gam.start(display,this);
		  
		  break;
	  case 5:  
		
		  try{
			 
			Manager.playTone(75, 1000, 200);
			}
		  catch(Exception  e)
		  {//e.printStackTrace();
                     debuginfo.append('\n'+e.getMessage());
		  }
		  break;
	  case 6:
              display.setCurrent(playermenu);
              
		  break;
    	  case 7:
		  display.setCurrent(debuginfo);
              break;
	  }
  }
  
  else if(c==Exit){
	writeTextFile(textfilename.getString(),editor.getString());
        writeTextFile(libraryfilename.getString(),musiclibrary.getString());
	  destroyApp(true);
	  notifyDestroyed();
  }
	  

  else if(c==EditorOptions)
  {display.setCurrent(editoroptions);
  }
  else if(c==ReloadEditor)
  {
      editor.setString(readFile(textfilename.getString()));
	  display.setCurrent(editor);
  }
  else if(c==SaveEditor)
  {writeTextFile(textfilename.getString(),editor.getString());
	  display.setCurrent(editor);
  }
  else if(c==Playcmd)
  {
      paused=false;
  int i,j,size;
          
          for(i=0,j=0;i<musiclibrary.getCaretPosition();i++)
                  {if(musiclibrary.getString().charAt(i)=='\n'||musiclibrary.getString().charAt(i)==0)j=i;}
          
          char[] musicdata=new char[musiclibrary.getMaxSize()];
        size=musiclibrary.getChars(musicdata);
        
for(i=1;(i+j-1)<size&&musicdata[i+j]!='\n'&&musicdata[i+j]!=0&&(i+j)<musiclibrary.getMaxSize();i++)
{i=i;}
                  //musicname[i]=0;
            //al.setString(String.valueOf(j)+" to "+String.valueOf(k)+" have "+String.valueOf(musicdata,j,i));
            //display.setCurrent(al);
                  //mp3name.setString(musiclibrary.getString().substring(j,k+1));
        if(j==0)mp3name.setString(String.valueOf(musicdata,j,i));
        else {mp3name.setString(String.valueOf(musicdata,j+1,i-1));}
          try {
              play = Manager.createPlayer(mp3name.getString());
          }  catch (Exception e) {
           debuginfo.append('\n'+e.getMessage());
          }
          try {
              play.start();
          }  catch (Exception e) {
           debuginfo.append('\n'+e.getMessage());
          }
  }
  else if(c==MusicEnter)
  {
	  switch(playermenu.getSelectedIndex())
          {
              case 0:
                    //play = Manager.createPlayer(mp3name.getString());
			//play.start();
          try {
              play = Manager.createPlayer(mp3name.getString());
              play.start();
              if(paused==true){play.setMediaTime(musicpos);paused=false;}
          }  catch (Exception e) {
          debuginfo.append('\n'+e.getMessage());
          }
                  break;
                  
         case 2:
             try{          
             musicpos=play.getMediaTime();
             }
              catch (Exception e) {
           debuginfo.append('\n'+e.getMessage());
          }
              paused=true;
         
                  
              case 1:
          try {
              play.stop();
              play.close();
                  play.deallocate();
          } catch (MediaException e) {
           debuginfo.append('\n'+e.getMessage());
          }
catch(IllegalStateException e)
{debuginfo.append('\n'+e.getMessage());
}
catch(NullPointerException e)
          {debuginfo.append('\n'+e.getMessage());}
                  
                  break;
                  
              case 3:
                 musiclibrary.setString(mp3name.getString()+'\n'+musiclibrary.getString());
                  break;
                  
              case 4:
                  visualplay=new playerthread(display,this,play);
                  display.setCurrent(visualplay);
               break;
              case 5:
                  display.setCurrent(musiclibrary);
                  break;
          }
          
  }
  //else cd.repaint();
	  }
  }
class playerthread extends Canvas implements Runnable,CommandListener
{

    boolean playing,closed,paused;
    Command mainscreen,restart,play;
midlet midlink;
Display d;
Thread t;
Player player;

int k,x,y,h,w,currentno;
long musicpos,dur;

    playerthread(Display disp,midlet mid,Player playerlink) {
        midlink=mid;
        d=disp;
        player=playerlink;
        paused=mid.paused;
        currentno=0;
        k=0;
        this.mainscreen = new Command("Main",Command.BACK,0);
        this.restart = new Command("Restart",Command.BACK,0);
        this.play = new Command("Play",Command.BACK,0);
        this.setFullScreenMode(true);
        this.addCommand(mainscreen);
        this.addCommand(restart);
        this.addCommand(play);
        this.setCommandListener(this);
        this.closed = false;
        this.playing = false;
repaint();
        t=new Thread(this);
t.start();
t.setPriority(10);
    }
    public void run() {
        
while(!closed)
		{ key();
                    repaint();
		try{
			synchronized(this)
			{wait(15L);}
		}
		catch(Exception e)
		{
			//e.printStackTrace();
			//debug.append(e.getMessage());
                        midlink.debuginfo.append('\n'+e.getMessage());
    }}}

    protected void keyPressed(int key)
	{k=key;repaint();}
	protected void keyReleased(int key)
	{k=0;repaint();}
	protected void keyRepeated(int key)
	{k=key;repaint();}
	protected void pointerPressed(int p1,int p2)
	{x=p1;y=p2;repaint();}
	protected void pointerReleased(int p1,int p2)
	{x=p1;y=p2;repaint();}
	protected void pointerDragged(int p1,int p2)
	{x=p1;y=p2;repaint();}
    
    public void commandAction(Command c, Displayable di) {
     if(c==mainscreen)
     {
         closed=true;
     d.setCurrent(midlink.mainmenu);
     }
     else if(c==play){k=53;playing=!playing;}
     else if(c==restart){currentno=0;k=53;playing=!playing;}
    }
void key()
{
    if(k==-4||k==54&&playing)
    {musicpos=player.getMediaTime();
    musicpos+=((float)player.getDuration())/10;
        try {
            player.setMediaTime(musicpos);
        }  catch (MediaException e) {
          midlink.debuginfo.append('\n'+e.getMessage());
          }
catch(IllegalStateException e)
{midlink.debuginfo.append('\n'+e.getMessage());
}
catch(NullPointerException e)
          {midlink.debuginfo.append('\n'+e.getMessage());}
}
   else if(k==-3||k==52&&playing)
    {musicpos=player.getMediaTime();
    musicpos-=((float)player.getDuration())/10;
        try {
            player.setMediaTime(musicpos);
        }  catch (MediaException e) {
           midlink.debuginfo.append('\n'+e.getMessage());
          }
catch(IllegalStateException e)
{midlink.debuginfo.append('\n'+e.getMessage());
}
catch(NullPointerException e)
          {midlink.debuginfo.append('\n'+e.getMessage());}
        
}
   else if(k==-1||k==50){
   currentno--;
   paused=false;
   if(playing){stopmusic();}
   playing=true;
   playmusic();
   }
   else if(k==-2||k==56){
   currentno++;
   paused=false;
   if(playing){stopmusic();}
   playing=true;
   playmusic();
   
   }
    else if(k==-5||k==53){if(!playing){k=0;playing=true;playmusic();}
else{
    if(player!=null){musicpos=player.getMediaTime();
    dur=player.getDuration();}
    paused=true;
    stopmusic();}}
else if(k==49){k=0;stopmusic();paused=false;}
else{repaint();return;}
    k=0;
}
    protected void paint(Graphics g) {
        h=g.getClipHeight();
        w=g.getClipWidth();
    
     //g.setColor(0x00FFFFFF);
     //g.fillRect(0,0,w,h);
        /*if(player!=null)
        {
        if(player.getState()==400)playing=true;
        else playing=false;
        }*/
        g.setColor(0x00FFFFFF);
        g.fillRect((w/10),(h/10),40,40);
     if(paused)g.setColor(0x00AAAADD);
     else if(playing)g.setColor(0x003333FF);
     else g.setColor(0x00FF0022);
     if(playing)g.fillTriangle((w/10)+40,(h/10)+20,(w/10),(h/10)+40,(w/10),(h/10));
     else if(paused){
         g.fillRect((w/10),(h/10),10,40);
         g.fillRect((w/10)+20,(h/10),10,40);}
     else {
     g.fillRect((w/10),(h/10),40,40);
     }
     
     
     g.setColor(0x00FFFFFF);
     g.fillRect(0,h-2*(h/10),w,2*(h/10));
     g.setColor(0x004444FF);
    
    g.drawString(midlink.mp3name.getString(),0,h-2*(h/10),0);
    if(player!=null)g.drawString(String.valueOf(player.getMediaTime()),0,h-(h/10),0);
    //if(player!=null) g.drawString(String.valueOf(player.getMediaTime()),0,h-2*(h/10),0);
    //if(player!=null) g.drawString(String.valueOf(player.getDuration()),0,h-h/10,0);
    //if(player!=null) g.drawString(String.valueOf((int)(w*((float)player.getMediaTime()/(float)player.getDuration()))),0,h-3*(h/10),0);
     g.setColor(0x0000FFFF);
     g.fillRect(0,h/2,w,h/10);
     if(paused)g.setColor(0x00AAAADD);
     else if(playing)g.setColor(0x003333FF);
     else g.setColor(0x00FF0022);
     if(player!=null)g.fillRect(0,h/2,(int)(w*((float)player.getMediaTime()/(float)player.getDuration())),h/10);
     else if(paused)g.fillRect(0,h/2,(int)(w*((float)(musicpos)/(float)(dur))),h/10);
     if(player!=null){if(player.getMediaTime()==player.getDuration()){currentno++;playmusic();}}
    }

    void playmusic()
    {
  int i,j,a,size;
          char[] musicdata=new char[midlink.musiclibrary.getMaxSize()];
        size=midlink.musiclibrary.getChars(musicdata);
          for(i=0,j=0,a=0;a<currentno&&i<size;i++)
                  {
                      if((i+1)>=size||midlink.musiclibrary.getString().charAt(i)==0){
                          currentno=0;a=0;i=0;j=0;
                      //midlink.al.setString("Big End");
                      //d.setCurrent(midlink.al);
                      }
                      else if(midlink.musiclibrary.getString().charAt(i)=='\n'){j=i;a++;}
                  }
         
for(i=1;(i+j-1)<size&&musicdata[i+j]!='\n'&&musicdata[i+j]!=0&&(i+j)<midlink.musiclibrary.getMaxSize();i++)
{if((i+j+1)>midlink.musiclibrary.getMaxSize()){currentno=0;i=0;j=0;}}
                  //musicname[i]=0;
            //midlink.al.setString(String.valueOf(j)+" at "+String.valueOf(currentno)+" have "+String.valueOf(musicdata,j,i));
            //d.setCurrent(midlink.al);
                  //mp3name.setString(musiclibrary.getString().substring(j,k+1));
        if(j==0)midlink.mp3name.setString(String.valueOf(musicdata,j,i));
        else {midlink.mp3name.setString(String.valueOf(musicdata,j+1,i-1));}
                   try {
               player = Manager.createPlayer(midlink.mp3name.getString());
              player.start();
              if(paused){player.setMediaTime(musicpos);paused=false;}
          }catch(IOException e)
          {midlink.debuginfo.append('\n'+e.getMessage());}
                   catch (MediaException e) {
          midlink.debuginfo.append('\n'+e.getMessage());
          }
catch(IllegalStateException e)
{midlink.debuginfo.append('\n'+e.getMessage());
}
catch(NullPointerException e)
          {midlink.debuginfo.append('\n'+e.getMessage());}
    }
void stopmusic()
{     
    playing=false;
try {
              player.stop();
              player.close();
              player.deallocate();
          } catch (MediaException e) {
          midlink.debuginfo.append('\n'+e.getMessage());
          }
catch(IllegalStateException e)
{midlink.debuginfo.append('\n'+e.getMessage());
}
catch(NullPointerException e)
          {midlink.debuginfo.append('\n'+e.getMessage());}
}
}